$(document).ready(function() {
    // 计算出货PCS数
    $(document).on('input', '.outbound-boxes', function() {
        const row = $(this).closest('tr');
        const boxSpec = row.find('[name="box_spec"]').val();
        const outboundBoxes = parseInt($(this).val()) || 0;

        if (boxSpec) {
            const pcs = outboundBoxes * parseInt(boxSpec);
            row.find('.outbound-pcs').text(pcs);
        }
    });

    // 提交表单
    $('#productOutboundForm').submit(function(e) {
        e.preventDefault();

        const formData = [];
        let hasOutbound = false;

        $('.form-row').each(function() {
            const outboundBoxes = parseInt($(this).find('.outbound-boxes').val()) || 0;

            if (outboundBoxes > 0) {
                hasOutbound = true;

                formData.push({
                    sku: $(this).find('[name="sku"]').val(),
                    box_spec: $(this).find('[name="box_spec"]').val(),
                    total_boxes: $(this).find('[name="total_boxes"]').val(),
                    outbound_boxes: outboundBoxes,
                    date: $(this).find('[name="date"]').val(),
                });
            }
        });

        if (!hasOutbound) {
            alert('请至少输入一条出库记录');
            return;
        }

        $.ajax({
            url: '',
            type: 'POST',
            data: {
                form_data: JSON.stringify(formData),
                csrfmiddlewaretoken: $('[name="csrfmiddlewaretoken"]').val()
            },
            success: function(response) {
                if (response.success) {
                    $('#successMessage').show();
                    setTimeout(function() {
                        $('#successMessage').hide();
                        location.reload(); // 刷新页面更新库存
                    }, 2000);
                }
            },
            error: function() {
                alert('出库失败，请稍后重试');
            }
        });
    });
});